<template>
  <div class="app-container">
    <PlatformHeader />
    <div class="main-container" :style="{ height: `calc(100vh - 72px)` }">
      <!-- 左侧面板 -->
      <div
        class="left-panel"
        :class="{ 'hidden': leftPaneSize === 0 }"
        :style="{ width: `${leftPaneSize}%` }"
      >
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入机构名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </div>

      <!-- 右侧主内容区 -->
      <div class="right-panel">
        <button
          class="toggle-btn"
          @click="toggleLeftPane"
          :style="{ left: leftPaneSize === 0 ? '10px' : `${leftPaneSize}%` }"
        >
          <i class="el-icon-s-fold" v-if="leftPaneSize > 0"></i>
          <i class="el-icon-s-unfold" v-else></i>
        </button>

        <el-col style="height: 100%;display: flex;flex-direction: column;padding-top: 20px">
          <el-form
            :model="form"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="90px"
            :rules="formRules"
            class="custom-form search-form"
          >
            <el-form-item label="机构" prop="deptId" required>
              <el-input
                v-model="selectedNodeInfo"
                placeholder="请从左侧选择机构"
                title="请从左侧选择机构"
                readonly
                clearable
                style="width: 220px;background-color: transparent;"
                @focus="handleInputFocus"
              />
            </el-form-item>

            <el-form-item label="下载项目" prop="testType" required>
              <el-select
                v-model="form.testType"
                placeholder="请选择下载项目"
                style="width: 220px"
                clearable
                @change="handleTestTypeChange"
                popper-class="custom-select-dropdown"
              >
                <el-option
                  v-for="item in testTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="日期范围" prop="dateRange" required>
              <el-date-picker
                popper-class="custom-select-dropdown"
                v-model="form.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 260px"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-download"
                size="mini"
                @click="handleQuery"
                class="search-btn action-btn"
                :disabled="!isFormValid"
                :loading="downloadLoading"
              >下载</el-button>
              <el-button icon="el-icon-refresh" size="mini" class="reset-btn action-btn" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 下载进度提示 -->
          <el-dialog
            title="下载进度"
            :visible.sync="progressDialogVisible"
            width="30%"
            :close-on-click-modal="false"
            :show-close="false"
            center
          >
            <div style="text-align: center">
              <el-progress
                :percentage="downloadProgress"
                :status="downloadStatus"
                :stroke-width="20"
                :text-inside="true"
              />
              <div style="margin-top: 20px">
                <span v-if="downloadStatus === 'success'">下载完成！</span>
                <span v-else-if="downloadStatus === 'exception'">下载失败！</span>
                <span v-else>正在下载，请稍候...</span>
              </div>
              <div style="margin-top: 20px">
                <el-button
                  type="primary"
                  size="small"
                  @click="progressDialogVisible = false"
                  v-if="downloadStatus !== ''"
                >确定</el-button>
              </div>
            </div>
          </el-dialog>

          <!-- 表格容器占满剩余空间 -->
          <div class="table-container">
          </div>
        </el-col>
      </div>
    </div>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";
import PlatformHeader from '../../../components/PlatformHeader/index.vue';
import { downloadExcelbydeptid } from "@/api/monitormanage/testpeoplelog";

export default {
  name: "Testpeople",
  components: { PlatformHeader },
  data() {
    const validateDateRange = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请选择日期范围'));
      } else {
        callback();
      }
    };

    const validateTestType = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择下载项目'));
      } else {
        callback();
      }
    };

    return {
      leftPaneSize: 16,
      form: {
        deptId: undefined,
        testType: null,
        dateRange: [],
        starttime: undefined,
        endtime: undefined
      },
      startYear: null, // 用于存储选择的开始年份
      loading: false,
      downloadLoading: false,
      showSearch: true,
      deptOptions: undefined,
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      testTypeOptions: [
        { value: 'testcorporeity', label: '国民体质' },
        { value: 'testturgoscope', label: '血压计' },
        { value: 'testpower', label: '功率车' },
        { value: 'testbodyfat', label: '体脂率' },
        { value: 'question', label: '问卷' }
      ],
      formRules: {
        deptId: [
          { required: true, message: '请选择机构', trigger: ['change', 'blur'] }
        ],
        testType: [
          { validator: validateTestType, trigger: ['change', 'blur'] }
        ],
        dateRange: [
          { validator: validateDateRange, trigger: ['change', 'blur'] }
        ]
      },
      selectedNodeInfo: '',

      // 下载进度相关
      progressDialogVisible: false,
      downloadProgress: 0,
      downloadStatus: '',
      downloadInterval: null,

      testPeopleList: [],
      pagedTestPeopleList: [],
      ids: [],
      single: true,
      multiple: true,

      // 日期选择器配置
      pickerOptions: {
        disabledDate: (time) => {
          // 如果没有选择开始日期或者已经清除了选择，只禁用未来日期
          if (!this.startYear) {
            return time.getTime() > Date.now();
          }

          // 如果已经选择了开始日期，限制只能选择同一年份
          const timeYear = time.getFullYear();
          return time.getTime() > Date.now() || timeYear !== this.startYear;
        },
        onPick: ({ maxDate, minDate }) => {
          if (minDate) {
            // 保存选中的开始日期年份
            this.startYear = minDate.getFullYear();
          } else {
            // 如果没有选择日期，清除年份限制
            this.startYear = null;
          }
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '本年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(end.getFullYear(), 0, 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  computed: {
    isFormValid() {
      return this.form.deptId && this.form.testType && this.form.dateRange && this.form.dateRange.length === 2;
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    toggleLeftPane() {
      this.leftPaneSize = this.leftPaneSize === 0 ? 16 : 0;
    },
    handleInputFocus() {
      this.leftPaneSize = 16;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.form.deptId = data.id;
      this.selectedNodeInfo = `${data.label} `;
      this.leftPaneSize = 0;
      this.$refs.queryForm.clearValidate(['deptId']);
    },
    handleTestTypeChange(val) {
      if (val) {
        this.$refs.queryForm.clearValidate(['testType']);
      }
    },
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.form.starttime = val[0];
        this.form.endtime = val[1];
        this.$refs.queryForm.clearValidate(['dateRange']);
      } else {
        this.form.starttime = undefined;
        this.form.endtime = undefined;
        this.form.dateRange = [];
      }
    },
    resetQuery() {
      this.form = {
        deptId: undefined,
        testType: null,
        dateRange: [],
        starttime: undefined,
        endtime: undefined
      };
      this.selectedNodeInfo = '';
      this.startYear = null;
      this.testPeopleList = [];
      this.pagedTestPeopleList = [];
      this.$refs.tree.setCurrentKey(null);
      this.$nextTick(() => {
        this.$refs.queryForm.clearValidate();
      });
    },

    // 下载ZIP文件（适配后端响应）
    handleQuery() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          const queryParams = {
            deptid: this.form.deptId,
            project: this.form.testType,
            starttime: this.form.starttime,
            endtime: this.form.endtime,
            year: this.form.starttime.substring(0, 4),
          };

          downloadExcelbydeptid(queryParams).then(response => {
            // 从响应中获取Blob对象（文件流）
            const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) // 根据实际文件类型调整 MIME type
            // 创建下载链接并触发下载
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(blob) // 创建指向Blob对象的URL
            downloadElement.href = href
            downloadElement.download = '体质测试数据.xlsx' // 设置下载的文件名，可由后端返回或固定
            document.body.appendChild(downloadElement)
            downloadElement.click() // 模拟点击下载链接
            document.body.removeChild(downloadElement) // 移除下载链接
            window.URL.revokeObjectURL(href) // 释放Blob对象的URL
          }).catch(error => {
            console.error('导出失败', error)
            this.$message.error('导出失败：' + (error.message || '未知错误')) // 提示错误信息
            this.loading = false
          })
        }
      });
    }


  },
  created() {
    this.getDeptTree();
  },
  beforeDestroy() {
    // 组件销毁时清理定时器，避免内存泄漏
    if (this.downloadInterval) {
      clearInterval(this.downloadInterval);
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('../../assets/images/bgn.png');
  background-size: 100% 100%;
  padding: 16px;
  box-sizing: border-box;
  padding-top: 0;
}

.main-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.left-panel {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #0160FA;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: width 0.3s ease;
  overflow: auto;
  padding: 16px;
  box-sizing: border-box;
}

.left-panel.hidden {
  width: 0 !important;
  padding: 0;
}

.right-panel {
  width: 100%;
  height: 100%;
  padding-left: 0;
  transition: padding-left 0.3s ease;
  box-sizing: border-box;
  overflow: auto;
}

.toggle-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  height: 30px;
  background-color: rgba(0,128,255,0.3);
  border: 1px solid #0080ff;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: left 0.3s ease;
}

.toggle-btn i {
  color: #fff;
  font-size: 10px;
}

.custom-form {
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 18px;
  }

  .el-form-item__label {
    white-space: nowrap;
    padding-right: 8px;
    color: #fff !important;
  }

  .el-input, .el-select, .el-date-editor {
    width: 220px;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 260px;
  }
}

::v-deep .el-tree {
  background: #0080FF;
  color: #fff;
  border-radius: 8px;
}

::v-deep .el-tree-node__content:hover {
  background-color: #0879e9;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #0879e9;
}

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  border-radius: 4px;
  background-color: rgba(240, 240, 240, 0.3);
}

::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: rgba(0, 128, 255, 0.5);
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 128, 255, 0.7);
}

::v-deep .el-input .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #00CCFE;
  border-radius: 6px;
  color: #f0f0f0;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  font-size: 14px;
  height: 36px !important;
  line-height: 36px !important;
}

::v-deep .el-input__inner::placeholder {
  color: #fff !important;
}

::v-deep .el-input .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.15);
  color: #fff;
}

::v-deep .el-form-item .el-button {
  border-radius: 22px;
  font-weight: 600;
  font-size: 15px;
  padding: 10px 28px;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(66, 133, 244, 0.3);
}

::v-deep .el-form-item .el-button--primary {
  background: linear-gradient(45deg, #409eff, #66b1ff);
  border: none;
  color: #fff;
  box-shadow: 0 5px 14px rgba(64, 158, 255, 0.6);
}

::v-deep .el-form-item .el-button--primary:hover {
  background: linear-gradient(45deg, #66b1ff, #409eff);
  box-shadow: 0 7px 18px rgba(64, 158, 255, 0.8);
}

::v-deep .el-date-editor {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid #00CCFE !important;
  border-radius: 6px;
  color: #f0f0f0 !important;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  height: 36px;
  line-height: 36px;
}

::v-deep .el-date-editor:hover {
  border-color: #409eff !important;
}

::v-deep .el-date-editor .el-input__inner {
  background-color: transparent !important;
  color: #fff !important;
}

::v-deep .el-date-editor .el-input__inner::placeholder {
  color: #fff !important;
}

::v-deep .el-select {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border-radius: 6px;
}

::v-deep .el-select .el-input__inner {
  background-color: transparent !important;
  color: #fff !important;
}

::v-deep .el-select .el-input__inner::placeholder {
  color: #fff !important;
}

::v-deep .el-select-dropdown {
  background-color: #0080FF !important;
  border: 1px solid #00CCFE !important;
}

::v-deep .el-select-dropdown__item {
  color: #fff !important;
}

::v-deep .el-select-dropdown__item.hover,
::v-deep .el-select-dropdown__item:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

::v-deep .el-select-dropdown__item.selected {
  background-color: rgba(64, 158, 255, 0.5) !important;
  color: #fff !important;
}
::v-deep .el-range-editor .el-range-input{
  background: transparent;
  color: #fff;

}
::v-deep .el-date-editor .el-range-separator{
  color: #fff;
}
/* 表单样式调整 */
.search-form {
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 18px;
  }

  .el-form-item__label {
    white-space: nowrap;
    padding-right: 8px;
    color: #fff!important;
  }
  ::v-deep .el-form-item__label {
    color: #fff;
  }
  .el-input, .el-select, .el-date-editor {
    width: 220px;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 260px;
  }
}
/* 调整表单里的按钮间距 */
::v-deep .el-form-item .el-button {
  margin-left: 12px; /* 你可以改成 16px 更宽松 */
}
/* 按钮通用样式（不改尺寸） */
::v-deep .el-form-item .action-btn {
  border-radius: 20px; /* 圆润 */
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}

/* 悬浮时按钮微微上浮 + 光晕 */
::v-deep .el-form-item .action-btn:hover {
  transform: translateY(-2px);
}

/* 搜索按钮 - 宝石蓝渐变 */
::v-deep .el-form-item .search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
}
::v-deep .el-form-item .search-btn:hover {
  background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
  box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
}

/* 重置按钮 - 高级灰蓝 */
::v-deep .el-form-item .reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
}
::v-deep .el-form-item .reset-btn:hover {
  background: linear-gradient(135deg, #ffcc80, #ffb74d);
  box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
}
</style>

